package com.zsc.oj.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zsc.oj.common.ErrorCode;
import com.zsc.oj.constant.CommonConstant;
import com.zsc.oj.constant.PostThumbRedisConstant;
import com.zsc.oj.exception.BusinessException;
import com.zsc.oj.exception.ThrowUtils;
import com.zsc.oj.mapper.PostThumbMapper;
import com.zsc.oj.model.dto.postThumb.PostThumbAddRequest;
import com.zsc.oj.model.dto.postThumb.PostThumbDeleteRequest;
import com.zsc.oj.model.dto.postThumb.PostThumbQueryRequest;
import com.zsc.oj.model.entity.PostThumb;

import com.zsc.oj.model.entity.User;
import com.zsc.oj.model.vo.PostThumbVO;
import com.zsc.oj.model.vo.UserVO;
import com.zsc.oj.service.PostThumbService;
import com.zsc.oj.service.UserService;
import com.zsc.oj.utils.SqlUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RSet;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 帖子点赞服务实现
 *
 * @author <a href="https://github.com/liyupi">程序员鱼皮</a>
 * @from <a href="https://www.code-nav.cn">编程导航学习圈</a>
 */
@Service
@Slf4j
public class PostThumbServiceImpl extends ServiceImpl<PostThumbMapper, PostThumb> implements PostThumbService {

    @Resource
    private UserService userService;

    @Resource
    private RedissonClient redissonClient;


    /**
     * 校验数据
     *
     * @param postThumb
     * @param add      对创建的数据进行校验
     */
    @Override
    public void validPostThumb(PostThumb postThumb, boolean add) {
        ThrowUtils.throwIf(postThumb == null, ErrorCode.PARAMS_ERROR);
        // todo 从对象中取值
        Long postId = postThumb.getPostId();
        Long userId = postThumb.getUserId();

        // 创建数据时，参数不能为空
        if (add) {
            // todo 补充校验规则
            ThrowUtils.throwIf(postId == null, ErrorCode.PARAMS_ERROR,"帖子id不存在");
            ThrowUtils.throwIf(userId == null, ErrorCode.PARAMS_ERROR,"未登录");
        }
    }

    /**
     * 获取查询条件
     *
     * @param postThumbQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<PostThumb> getQueryWrapper(PostThumbQueryRequest postThumbQueryRequest) {
        QueryWrapper<PostThumb> queryWrapper = new QueryWrapper<>();
        if (postThumbQueryRequest == null) {
            return queryWrapper;
        }
        // todo 从对象中取值
        Long id = postThumbQueryRequest.getId();
        Long notId = postThumbQueryRequest.getNotId();
        String title = postThumbQueryRequest.getTitle();
        String content = postThumbQueryRequest.getContent();
        String searchText = postThumbQueryRequest.getSearchText();
        String sortField = postThumbQueryRequest.getSortField();
        String sortOrder = postThumbQueryRequest.getSortOrder();
        List<String> tagList = postThumbQueryRequest.getTags();
        Long userId = postThumbQueryRequest.getUserId();
        // todo 补充需要的查询条件
        // 从多字段中搜索
        if (StringUtils.isNotBlank(searchText)) {
            // 需要拼接查询条件
            queryWrapper.and(qw -> qw.like("title", searchText).or().like("content", searchText));
        }
        // 模糊查询
        queryWrapper.like(StringUtils.isNotBlank(title), "title", title);
        queryWrapper.like(StringUtils.isNotBlank(content), "content", content);
        // JSON 数组查询
        if (CollUtil.isNotEmpty(tagList)) {
            for (String tag : tagList) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 精确查询
        queryWrapper.ne(ObjectUtils.isNotEmpty(notId), "id", notId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        // 排序规则
        queryWrapper.orderBy(SqlUtils.validSortField(sortField),
                sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }

    /**
     * 获取帖子点赞封装
     *
     * @param postThumb
     * @param request
     * @return
     */
    @Override
    public PostThumbVO getPostThumbVO(PostThumb postThumb, HttpServletRequest request) {
        // 对象转封装类
        PostThumbVO postThumbVO = PostThumbVO.objToVo(postThumb);

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Long userId = postThumb.getUserId();
        User user = null;
        if (userId != null && userId > 0) {
            user = userService.getById(userId);
        }
        UserVO userVO = userService.getUserVO(user);
        postThumbVO.setUser(userVO);
        // endregion

        return postThumbVO;
    }

    /**
     * 分页获取帖子点赞封装
     *
     * @param postThumbPage
     * @param request
     * @return
     */
    @Override
    public Page<PostThumbVO> getPostThumbVOPage(Page<PostThumb> postThumbPage, HttpServletRequest request) {
        List<PostThumb> postThumbList = postThumbPage.getRecords();
        Page<PostThumbVO> postThumbVOPage = new Page<>(postThumbPage.getCurrent(), postThumbPage.getSize(), postThumbPage.getTotal());
        if (CollUtil.isEmpty(postThumbList)) {
            return postThumbVOPage;
        }
        // 对象列表 => 封装对象列表
        List<PostThumbVO> postThumbVOList = postThumbList.stream().map(postThumb -> {
            return PostThumbVO.objToVo(postThumb);
        }).collect(Collectors.toList());

        // todo 可以根据需要为封装对象补充值，不需要的内容可以删除
        // region 可选
        // 1. 关联查询用户信息
        Set<Long> userIdSet = postThumbList.stream().map(PostThumb::getUserId).collect(Collectors.toSet());
        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
                .collect(Collectors.groupingBy(User::getId));
        // endregion

        postThumbVOPage.setRecords(postThumbVOList);
        return postThumbVOPage;
    }

    /**
     * 使用redis实现点赞
     * @param postThumbAddRequest
     * @return
     */
    @Override
    public boolean addPostThumb(PostThumbAddRequest postThumbAddRequest) {
        Long postId = postThumbAddRequest.getPostId();
        Long userId = postThumbAddRequest.getUserId();
        if(postId == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"postId为空");
        }
        if(userId == null){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"userId为空");
        }
        RSet<Object> set = redissonClient.getSet(PostThumbRedisConstant.getUserKey(userId));
        if(!set.add(postId)){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"请勿重复点赞");
        }else{
            //将数据持久化到mysql中
            return this.addPostThumbToMysql(postThumbAddRequest);
        }
    }

    /**
     * redis删除点赞
     * @param postThumbDeleteRequest
     * @return
     */
    @Override
    public boolean deletePosThumb(PostThumbDeleteRequest postThumbDeleteRequest,HttpServletRequest request) {
        Long userId = postThumbDeleteRequest.getUserId();
        Long postId = postThumbDeleteRequest.getPostId();
        if(postId == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"postId为空");
        }
        if(userId == null){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"userId为空");
        }
        RSet<Object> set = redissonClient.getSet(PostThumbRedisConstant.getUserKey(userId));
        boolean remove = set.remove(postId);
        if(remove){
            return this.deletePostThumbToMysql(postThumbDeleteRequest,request);
        }else{
            throw new BusinessException(ErrorCode.SYSTEM_ERROR);
        }
    }

    /**
     * 将数据写入mysql
     * @param postThumbAddRequest
     * @return
     */
    public boolean addPostThumbToMysql(PostThumbAddRequest postThumbAddRequest){
        //不能重复点赞
        QueryWrapper<PostThumb> postThumbQueryWrapper = new QueryWrapper<>();
        postThumbQueryWrapper.eq("postId",postThumbAddRequest.getPostId());
        postThumbQueryWrapper.eq("userId",postThumbAddRequest.getUserId());
        PostThumb isHavePostThumb = this.getOne(postThumbQueryWrapper);
        if(isHavePostThumb == null){
            // 写入数据库
            PostThumb postThumb = new PostThumb();
            postThumb.setPostId(postThumbAddRequest.getPostId());
            postThumb.setUserId(postThumbAddRequest.getUserId());
            boolean result = this.save(postThumb);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        }else{
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"请勿重复点赞");
        }
        return true;
    }

    /**
     * 删除mysql的点赞记录
     * @param postThumbDeleteRequest
     * @return
     */
    public boolean deletePostThumbToMysql(PostThumbDeleteRequest postThumbDeleteRequest,HttpServletRequest request){
        User user = userService.getLoginUser(request);
        // 判断是否存在
        QueryWrapper<PostThumb> postThumbQueryWrapper = new QueryWrapper<>();
        postThumbQueryWrapper.eq("postId",postThumbDeleteRequest.getPostId());
        postThumbQueryWrapper.eq("userId",postThumbDeleteRequest.getUserId());
        PostThumb oldPostThumb = this.getOne(postThumbQueryWrapper);
        ThrowUtils.throwIf(oldPostThumb == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldPostThumb.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库

        boolean result = this.removeById(oldPostThumb);

        return result;
    }

}
